# Obtain command line arguments from .sh file

args=(commandArgs(TRUE))

# Evaluate the arguments for use in this script

for(i in 1:length(args)) 
	
	{
		
	eval(parse(text=args[[i]]))
 
	}
	
# Establish directories

#out.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/microCLIMyearly/'
out.dir = '/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/microCLIMweeklyaggregate/'


# Load the library

library('SDMTools')

# Location of ASCII files for yearx

tmax.dir = paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/maxgzip/',yearx,'/',sep='')
tmin.dir = paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/brtpredsfinal/mingzip/',yearx,'/',sep='')

# ASCII files for each day of yearx, full path name to ease use of scan command

tmax.files = list.files(tmax.dir, pattern='.asc.gz', full.names=T)
tmin.files = list.files(tmin.dir, pattern='.asc.gz', full.names=T)

# Use a for loop to individually read in ASCII files for each day yearx
# Create a matrix from these files that has columns equal to the number of days in the month
# And rows equal to the number of finite positions in the ASCII file

tmin.data = NULL
tmax.data = NULL
yearx.min.data = NULL
yearx.max.data = NULL

# Need to read in DEM ASCII because I only want to perform calculations for positions where DEM ASCII is finite

dem.asc = read.asc('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/STATIC/dem_WTplusbuffer_LatLong_WGS1984_250mres.asc')

### Week adjuster

wa = 0

for (ii in c(1:52))

	{
	
	# Subset tmax and tmin files by ii (week)
	#ttmax.files = tmax.files[which(as.numeric(substr(tmax.files,100,101))==ii)]
	#ttmin.files = tmin.files[which(as.numeric(substr(tmin.files,100,101))==ii)]
	
	ttmax.files = tmax.files[c(1:7)+wa]
	ttmin.files = tmin.files[c(1:7)+wa]
	
	wa = wa+7

	for (i in c(1:length(ttmax.files)))
		
		{
		
		tmax.file = read.asc.gz(paste(ttmax.files[i],sep='')) # Read in the ASCII file for day i
		tmin.file = read.asc.gz(paste(ttmin.files[i],sep=''))
		
		tmax.file = tmax.file[which(is.na(dem.asc)==F)] # Remove positions that are NA, based on finite positions in dem.asc
		tmin.file = tmin.file[which(is.na(dem.asc)==F)] # Remove positions that are NA
		
		
		if(length(which(is.na(tmax.file)==T))==0) # Some AWAP files contain NA's, these can't be column binded onto the summary dataframe, or they will fuckup the following rowMeans call
			
			{
			
			if(length(which(is.na(tmin.file)==T))==0)
			
				{
						
				tmax.data = cbind(tmax.data,tmax.file) # Bind tmax.file to blank object
				tmin.data = cbind(tmin.data,tmin.file) # Bind tmin.file to blank object
				
				}
				
			}
				
				if(i==length(ttmax.files)) # Perform calculations for days in the month when i equals the final day of the month
		
					{

					# Use rowMeans to aggregate the data
					# Creates a vector of the length of finite positions in tmax.file
					# Which is the mean temperature for that position across all days in that month
		
					tmax.summary = rowMeans(tmax.data)
					tmin.summary = rowMeans(tmin.data)
				
					tmin.data = NULL
					tmax.data = NULL
				
					}
					
		}
		
	# Need to bind tmax.summary and tmin.summary for each month into a single matrix of 12 columns and 1 row for each finite position in dem.asc
	
	cat(ii,'\n')
	
	yearx.max.data = cbind(yearx.max.data,tmax.summary)
	yearx.min.data = cbind(yearx.min.data,tmin.summary)
	
	# Write out summary dataframes to out.dir
	
	if(ii==52)
	
	{
	
	yearx.max.data = round(yearx.max.data,2)
	yearx.min.data = round(yearx.min.data,2)
	
	write.csv(yearx.max.data, file=paste(out.dir,yearx,'/','meanmax',yearx,'.csv',sep=''),row.names=F)
	write.csv(yearx.min.data, file=paste(out.dir,yearx,'/','meanmin',yearx,'.csv',sep=''),row.names=F)
	
	}
	
	}
	
# Close loop

#for (yearx in 1977:2005)

#	{
	
#	dir.create(paste('/home1/99/jc152199/MicroclimateStatisticalDownscale/250mASCII/microCLIMweeklyaggregate/',yearx,sep=''))
	
#	}
	
# Close loop